package br.ufrj.dcc.ad.main;

import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import br.ufrj.dcc.ad.args.ParameterBuilder;
import br.ufrj.dcc.ad.args.SimulationParameters;
import br.ufrj.dcc.ad.log.LoggerFactory;
import br.ufrj.dcc.ad.log.config.ResourceLoader;
import br.ufrj.dcc.ad.systems.Controlador;

public class Main {
	private static String applicationName = "java -jar Trabalho_Simulacao.jar";
	private static Logger log = LoggerFactory.getLogger(LoggerFactory.Type.RAW_STDOUT);
	
	static {
		configuraLog();
	}
	
	public static void main(String[] args) {
		
		ParameterBuilder p = new ParameterBuilder(args);
		Controlador controlador = null;
		
		try {
			Map<SimulationParameters, String> params = p.build();
			if(params.containsKey(SimulationParameters.HELP) || params.isEmpty()) {
				log.info(getMensagemUso(p));
				return;
			}
			
			StringBuffer sb = new StringBuffer();
			for(String s : args) {
				sb.append(s).append(" ");
			}
			
			controlador = new Controlador();
			
//			ConsoleWorker worker = new ConsoleWorker(simulacao);
//			worker.start();
			
			controlador.inicializarParametrosSimulacao(params);
			log.info("Simulacao iniciada com parametros: " + sb);
			controlador.simula(params);
			
		} catch(IllegalArgumentException e) {
			log.info("Parametro " + controlador.getParametroErrado() + " esta faltando");
			log.info(getMensagemUso(p));
		}
	}

	private static void configuraLog() {
		LoggerFactory.clearAllLogs();
		PropertyConfigurator.configure(ResourceLoader.getResource("log4j.properties"));
	}
	
	private static String getMensagemUso(ParameterBuilder p) {
		StringBuffer output = new StringBuffer();
		output.append("Uso: " + applicationName + " [Opcoes]\n");
		output.append("\tOpcoes:\n");
		output.append(p.getParametersList("\t"));
		
		return output.toString();
	}
}
